/**
 * Metro configuration for React Native
 * https://github.com/facebook/react-native
 *
 * @format
 */
const fs = require('fs');
const crypto = require('crypto');
const request = require('sync-request');
const pathUtil = require('path');
const urlUtil = require('url');

/********** Global Module Id Service ***********/

var serverBaseUrl = 'http://localhost:3210';

function setBaseUrl(inputUrl) {
  serverBaseUrl = inputUrl;
}

function getAllModuleIdsSync() {
  var reqUrl = urlUtil.resolve(serverBaseUrl, 'module/ids');
  console.log(`getAllModuleIdsSync url= ${reqUrl}`);
  var res = request('GET', reqUrl);
  return JSON.parse(res.getBody('utf8'));
}

function createModuleIdSync(
  findKey,
  relativePath,
  hashInHex,
  hashType,
  size,
  type,
) {
  let requestData = {
    findKey: findKey,
    relativePath: relativePath,
    hashInHex: hashInHex,
    hashType: hashType,
    size: size,
    type: type,
  };
  var reqUrl = urlUtil.resolve(serverBaseUrl, 'module/id/create');
  var res = request('POST', reqUrl, {
    json: requestData,
  });
  return JSON.parse(res.getBody('utf8'));
}

/********** Tools ***********/

function getFileRelativePath(projectRootPath, path) {
  let relativePath = path;
  if (path.indexOf(projectRootPath) == 0) {
    relativePath = path.substr(projectRootPath.length + 1);
  }
  return relativePath;
}

function getFileHashInHex(path, hashType) {
  let hash = crypto.createHash(hashType);
  let fileConentBuffers = fs.readFileSync(path);
  hash.update(fileConentBuffers);
  return hash.digest('hex');
}

function buildFindKey(relativePath, hashInHex) {
  let sha256 = crypto.createHash('sha256');
  sha256.update(`${hashInHex}${relativePath}`);
  let findKey = sha256.digest('hex');
  return findKey;
}

function saveDataToFile(filePath, data) {
  let dir = pathUtil.dirname(filePath);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir);
  }
  fs.writeFileSync(filePath, data);
}

function getCurrentTimestamp() {
  return new Date().getTime();
}

module.exports = {
  setBaseUrl: setBaseUrl,
  getAllModuleIdsSync: getAllModuleIdsSync,
  createModuleIdSync: createModuleIdSync,
  getFileRelativePath: getFileRelativePath,
  getFileHashInHex: getFileHashInHex,
  buildFindKey: buildFindKey,
  saveDataToFile: saveDataToFile,
  getCurrentTimestamp: getCurrentTimestamp,
};
